﻿using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VIA.Integration.Domain;
using VMathNet.Numerics.LinearAlgebra.Factorization;

namespace VIA.SiMoJi.Domain
{
    [AddINotifyPropertyChangedInterface]
    public class CalcTimeEventArgs : EventArgs
    {
        public CalcTimeOption Option { get; }
        public CalcTimeEventArgs(CalcTimeOption option)
        {
            Option = option;
        }
    }

    public interface ICalcTimeService
    {
        event EventHandler<CalcTimeEventArgs> OnCalcTimeChanged;
        void CalcCT();
        void CalcQuality(Quality quality, int count);
        Task Zero();
        void Load();
        Task Save();
    }

    /// <summary>
    /// 计算CT服务
    /// </summary>
    internal class CalcTimeService : ICalcTimeService
    {
        readonly IOptionRepository _optionRepository;
        readonly IDataStorageService _dataStorageService;
        public event EventHandler<CalcTimeEventArgs> OnCalcTimeChanged;
        DateTime preCurrentTime = default;
        public CalcTimeOption Option { get; set; }
        public CalcTimeService(IOptionRepository optionRepository, IDataStorageService dataStorageService)
        {
            _optionRepository = optionRepository;
            _dataStorageService = dataStorageService;
        }
        public void CalcCT()
        {
            if (preCurrentTime == default)
            {
                preCurrentTime = DateTime.Now;
            }
            else
            {
                var timeSpan = DateTime.Now - preCurrentTime;
                Option.CurrentCT = timeSpan.TotalSeconds / 84;
                OnCalcTimeChanged(this, new CalcTimeEventArgs(Option));
                preCurrentTime = DateTime.Now;
            }
        }
        public void CalcQuality(Quality quality, int count)
        {
            if (quality == Quality.Ok)
            {
                Option.OK = Option.OK + count;
            }
            else
            {
                Option.NG = Option.NG + count;
            }
            OnCalcTimeChanged(this, new CalcTimeEventArgs(Option));
        }
        public void Load()
        {
            Option = _optionRepository.Get<CalcTimeOption>();
            OnCalcTimeChanged(this, new CalcTimeEventArgs(Option));
        }
        public async Task Save()
        {
            _optionRepository.Set(Option);
            await _optionRepository.SaveAsync();
        }

        public async Task Zero()
        {
            _dataStorageService.SaveDataCsv(Option);
            Option = new CalcTimeOption() { NG = 0, OK = 0 };
            await Save();
            Load();
        }
    }
}
